package com.nulldev.util.web.flexibleKit.scfk.protocols.gopher;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.web.flexibleKit.scfk.SCFKRequest;
import com.nulldev.util.web.flexibleKit.scfk.SCFKResponse;
import com.nulldev.util.web.flexibleKit.scfk.io.streams.Stream;
import com.nulldev.util.web.flexibleKit.scfk.io.streams.StreamGenerator;
import com.nulldev.util.web.flexibleKit.scfk.protocols.PreferredProtocol;
import com.nulldev.util.web.flexibleKit.scfk.protocols.ProtocolRequest;

public class GopherRequest implements ProtocolRequest {

	public static final GopherRequest INSTANCE = new GopherRequest();

	@Override
	public SCFKResponse onRequestWrite(final SCFKRequest r, final Stream s) throws Exception {
		if (r.getProtocol() != PreferredProtocol.GOPHER)
			throw new UnsupportedOperationException("Cannot use a non-GOPHER protocol!");
		final String path = r.getURL().getRawPath() + (r.getURL().getQuery() != null ? "?" + r.getURL().getQuery() : "");
		s.printAll(path);
		return GopherResponse.INSTANCE.onResponseRead(r, s);
	}

	@Override
	public String getProtocolName() {
		return "Gopher";
	}

	@Override
	public String getProtocolVersion() {
		return "1.0";
	}

	@Override
	public double implementationVersion() {
		return 0.01;
	}

	public static void main(String[] args) throws Exception {
		final SCFKRequest r = new SCFKRequest("gopher://gopher.quux.org:70/");
		r.setPreferredProtocol(PreferredProtocol.GOPHER);
		final SCFKResponse s = INSTANCE.onRequestWrite(r, StreamGenerator.autoStream(r));
		JVM.println(s.asString());
		s.adaptiveClose();
	}

}
